package com.briup.estore.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author adam
 * @date 2023/4/3
 * 用户过滤  如果session中没有user对象需要先登录再执行操作
 */
@WebFilter(urlPatterns = {"/toCollect","/toViewShop"})
@Slf4j
public class UserFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.debug("into filter");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Object o = req.getSession().getAttribute("user");
        if (o == null) {
            log.debug("no user login");
            //内部跳转
            req.setAttribute("msg", "您还未登录 请先登录！");
            request.getRequestDispatcher("toLogin").forward(request, response);

            //    重定向
            //resp.sendRedirect("/toLogin");
        }
        //将web请求响应对继续交给 过滤器链
        chain.doFilter(request, response);
    }
}
